package browser
{
	import caurina.transitions.Tweener;
	
	import datas.GlobalDatas;
	
	import events.GlobalEvents;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Matrix;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import uiobj.ListThumb;

	public class SingleView extends Sprite
	{
		private var thumb:ListThumb;
		private var display:Boolean = false;
		private var img:DisplayObject;
		private var orgWidth:Number;
		private var orgHeight:Number;
		
		public function SingleView()
		{
		}
		
		public function load():void
		{
			GlobalEvents.dispatcher.addEventListener(GlobalEvents.VIEW_SINGLE_LOAD, singleLoad);
			GlobalEvents.dispatcher.addEventListener(GlobalEvents.STAGE_RESIZED, onStageResize);
			addEventListener(MouseEvent.CLICK, onMouseClick);
		}
		
		private function singleLoad(e:Event):void
		{
			var request:URLRequest = new URLRequest(GlobalDatas.currentPhoto.url);
			var loader:Loader = new Loader;
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
			loader.load(request);
		}
		
		private function onComplete(e:Event):void
		{
			img = e.target.content;
			orgWidth = img.width;
			orgHeight = img.height;
			
			resizePhoto();
			this.x = GlobalDatas.stagewidth;
			addChild(img);
			display = true;
			singleViewPosition();
			GlobalEvents.dispatcher.dispatchEvent(new Event(GlobalEvents.HIDE_LIST));
		}
		
		private function resizePhoto():void
		{
			
			var scalefact:Number = GlobalDatas.stagewidth / orgWidth;
			
			if(GlobalDatas.stageheight < scalefact * orgHeight)
				scalefact = GlobalDatas.stageheight / orgHeight;
			
			img.scaleX = scalefact;
			img.scaleY = scalefact;
			
			img.x = (GlobalDatas.stagewidth - img.width) / 2;
			img.y = (GlobalDatas.stageheight - img.height) / 2;
		}
		
		private function onStageResize(e:Event):void
		{
			trace("onStageResize");
			resizePhoto();
			display = true;
			singleViewPosition();
		}
		
		private function singleViewPosition():void
		{
			if(display == true)
				Tweener.addTween(this,{x:0,time:1});
			else
				Tweener.addTween(this,{x:GlobalDatas.stagewidth,time:1});
		}
		
		private function onMouseClick(e:MouseEvent):void
		{
			GlobalEvents.showList();
		}
	}
}